#!/usr/bin/env python

import sys
from kismet import Kismet

def bssidcb(proto, fields):
    global bssids, clients
    if fields['channel'] != '0':
        bssids.append(fields)
    else:
        clients.append(fields)
    
def ssidcb(proto, fields):
    global ssids
    ssids.append(fields) 
    
def ackcb(id, text): 
    print "Subscription #%i %s" % (id, text)
    global k, bssids, ssids, aps, clients
    # Checking for 1 here, because ackbacks doesn't get removed until after it is called:
    if len(k.ackbacks) == 1:
        k.kill()
        for ssid in ssids:
            for bssid in bssids:
                if ssid['mac'] == bssid['bssid']:
                    ap = {'bssid': bssid['bssid'], 'ssid': ssid['ssid'], 'manuf': bssid['manuf'], 'channel': bssid['channel'], 'signal': bssid['signal_dbm'], 'secured': bool(int(ssid['cryptset'])), 'cloaked': bool(int(ssid['cloaked']))}
                    aps.append(ap)
        for ap in aps:
            print 'Kismet saw %(manuf)s access point broadcasting %(ssid)s (%(bssid)s) on channel %(channel)s.' % ap
        print 'There are %i clients broadcasting.' % len(clients)

def main():
    global k
    k.start()
    k.subscribe("bssid", ["bssid", "manuf", "channel", "signal_dbm"], lambda *args: bssidcb(*args), lambda *args: ackcb(*args))
    k.subscribe("ssid", ["mac", "ssid", "cryptset", "cloaked"], lambda *args: ssidcb(*args), lambda *args: ackcb(*args))
    #k.wait()
    try:
        while k.isAlive(): pass
    except KeyboardInterrupt:
        print 'Killing thread...'
        k.kill()
    
if __name__ == '__main__':
    k = Kismet()
    bssids = [ ]
    ssids = [ ]
    aps = [ ]
    clients = [ ]
    main()
    